package com.grad.why.studentsystem.controller;

import com.grad.why.studentsystem.domain.*;
import com.grad.why.studentsystem.domain.current.CurrentModuleAndMenuInfos;
import com.grad.why.studentsystem.domain.current.CurrentStudentEvaluateInfo;
import com.grad.why.studentsystem.service.*;
import com.grad.why.studentsystem.service.impl.CustomMultiThreadingService;
import com.grad.why.studentsystem.util.RandomValidateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/studentManageSystem")
public class StudentController {

    private static final String OK = "OK";

    private static final String FAILED = "FAILED";

    @Autowired
    private OptionparamsService optionparamsService;

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private TeacherService teacherService;

    @RequestMapping("/login")
    public String goToLogin() throws Exception {
        return "index";
    }

    @RequestMapping(value="/checkCode")
    public void checkCode(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置相应类型,告诉浏览器输出的内容为图片
        response.setContentType("image/jpeg");

        //设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);

        RandomValidateCode randomValidateCode = new RandomValidateCode();
        try {
            randomValidateCode.getRandcode(request, response);//输出图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //登录校验
    @RequestMapping("/checkLogin")
    @ResponseBody
    public User checkLogin(HttpServletRequest request,String username,String password,String code){
        try {
            int n = userService.checkUserIsExistByUserName(username);
            if(n==0){
                return null;
            }else{
                HttpSession session = request.getSession();
                String randCode = (String)session.getAttribute("randomcode_key");
                if(randCode.toLowerCase().equals(code.toLowerCase())){
                    User user = userService.getUserByUserNameAndPassword(username);
                    if(user.getPassword().equals(password)){
                        session.setAttribute("user",user);
                        int type = user.getType();
                        int bindid = user.getBindid();
                        session.setAttribute("type",type);
                        session.setAttribute("bindid",bindid);
                        String infos = "";
                        if(type == 1){
                            Admin admin = adminService.getAdminByBindId(bindid);
                            infos = "管理员_"+admin.getName();
                        }else if(type == 2){
                            Teacher teacher = teacherService.getTeacherInfoByTid(bindid);
                            infos = "教师_"+ teacher.getName();
                        }else if(type == 3){
                            Student student = studentService.getStudentInfoBySid(bindid);
                            infos = "班干部_"+ student.getName();
                        }else if(type == 4){
                            Student student = studentService.getStudentInfoBySid(bindid);
                            infos = "学生_"+ student.getName();
                        }
                        session.setAttribute("infos",infos);
                        return user;
                    }else{
                        return null;
                    }
                }else{
                    return null;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/goToStarter")
    public String goToStarter(HttpServletRequest request,ModelMap modelMap){
        User user = ((User)request.getSession().getAttribute("user"));
        int type = user.getType();
        ArrayList<Menu> menuinfos = menuService.getMenuInfosByUserType(type);
        List<Integer> IdList = new ArrayList<Integer>();
        for(Menu menu : menuinfos){
            if(!IdList.contains(menu.getModuleid())){
                IdList.add(menu.getModuleid());
            }
        }
        List<CurrentModuleAndMenuInfos> moduleinfos = new ArrayList<CurrentModuleAndMenuInfos>();
        for(Integer i : IdList){
            Moduleinfos infos = menuService.getCurrentStudentEvaluateInfoById(i);
            CurrentModuleAndMenuInfos currentModuleAndMenuInfos = new CurrentModuleAndMenuInfos();
            currentModuleAndMenuInfos.setModuleid(infos.getModuleid());
            currentModuleAndMenuInfos.setModulename(infos.getModulename());
            for(Menu m : menuinfos){
                if(m.getModuleid() == i){
                    currentModuleAndMenuInfos.getMenuList().add(m);
                }
            }
            moduleinfos.add(currentModuleAndMenuInfos);
        }

        modelMap.addAttribute("modualinfos",moduleinfos);
        return "starter";
    }

    @RequestMapping("/signOut")
    public String signOut(HttpServletRequest request){
        try{
            HttpSession session = request.getSession();
            session.removeAttribute("user");
            session.removeAttribute("infos");
            session.removeAttribute("type");
            session.removeAttribute("bindid");
        }catch (Exception e){
            e.printStackTrace();
        }
        return "index";
    }

    @RequestMapping("/getStudentList")
    @ResponseBody
    public Object getStudentList(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, defaultValue = "", value = "search") String search,
            @RequestParam(required = false, value = "order") String order
    ) {
        try {
            List<Student> rows = studentService.getStudentList(offset, limit, sort, search);
            long total = studentService.getStudentListLength(search);
            Map<String, Object> result = new HashMap<>(2);
            result.put("rows", rows);
            result.put("total", total);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/addStudent")
    @ResponseBody
    public Student addStudent(Student student,String transbirthday){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            student.setBirthday(sdf.parse(transbirthday));
            int maxId = studentService.getMaxStudentId();
            student.setId(maxId + 1);
            Student stu = studentService.addStudentByEntity(student);
            return stu;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/updateStudent")
    @ResponseBody
    public Student updateStudent(Student student,String transbirthday){
        try{
            Integer sid = student.getId();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            student.setBirthday(sdf.parse(transbirthday));
            Student stu = studentService.updateStudentByEntity(student);
            return stu;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/deleteStudent/{ids}")
    @ResponseBody
    public String deleteStudentByIds(@PathVariable("ids") String ids){
        try{
            String[] idArray = ids.split("-");
            boolean flag = true;
            for(String s : idArray){
                Integer id = Integer.parseInt(s);
                int rows = studentService.deleteStudentById(id);
                if(rows == -1){
                    flag = false;
                    break;
                }
            }
            if(!flag){
                return FAILED;
            }else{
                return OK;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return FAILED;
    }

    @RequestMapping("/uploadStudentInfos")
    @ResponseBody
    public String uploadStudentInfos(@RequestParam("file") MultipartFile file){
        try{
            String fileUploadRootPath = optionparamsService.getParamValueByParamName("fileRootPath");
            String fileName = file.getOriginalFilename();
            String uploadCurrentFileName = fileUploadRootPath+"uploadStudentInfo/"+ new Date().getTime() + fileName;

            File fileRootPath = new File(fileUploadRootPath+"uploadStudentInfo");

            if(!fileRootPath.exists()){
                fileRootPath.mkdirs();
            }

            FileOutputStream out = new FileOutputStream(uploadCurrentFileName);
            out.write(file.getBytes());
            out.flush();
            out.close();

            int n = studentService.addStudentInfosByExcelFile(uploadCurrentFileName);
            if(n<=0){
                return "添加失败";
            }else{
                return "添加"+n+"条数据";
            }
            //上传学生信息逻辑
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
